package com.hhxy.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录验证的过滤器
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //强转以下，它的子类功能更加强大
        HttpServletRequest req = (HttpServletRequest) request;
        //与登录无关的资源（比如css，js） 还有登录和注册（不放行登录就死锁了） 直接放行
        String[] urls = {"/login.jsp","/imgs/","/css/","/js","/register.jsp",
                "/LoginServlet","/RegisterServlet","/CheckCodeServlet"};
        //获取访问的资源对象
        String url = req.getRequestURL().toString();
        System.out.println(url);
        //判断访问资源是否为放行资源
        for (String u : urls) {
            if(url.contains(u)){
                //属于放行的资源，放行
                chain.doFilter(request,response);
                //防止放行完有执行放行后的代码
                return;//是放行资源，就不需要判断下面的代码了
            }
        }

        System.out.println("hahaha");
        //1、判断Session中是否由User对象
        //1.1 将ServletRequest强转成HttpServlet(向下转型)，才能获取Session对象
        //1.2 获取Session对象
        HttpSession session = req.getSession();
        //1、3 获取Session域中的User对象
        Object user = session.getAttribute("user");
        //1.4 判断是否为空
        if(user != null){
            //已经登录，放行
            chain.doFilter(request, response);
        }else{
            //未登录，不放行，同时存储提示信息
            req.setAttribute("login_msg","您尚未登录");
            //这里用哪一个request对象都可以，强换只是为了存数据
            req.getRequestDispatcher("/jsp/login.jsp").forward(req,response);
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
